package org.nyt.medicalstore.service.impl;

import org.apache.coyote.BadRequestException;
import org.nyt.medicalstore.model.Drug;
import org.nyt.medicalstore.model.DrugSimilarity;
import org.nyt.medicalstore.repository.DrugRepository;
import org.nyt.medicalstore.repository.DrugSimilarityRepository;
import org.nyt.medicalstore.service.DrugSimilarityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class DrugSimilarityServiceImpl implements DrugSimilarityService {
    @Autowired
    private DrugRepository drugRepository;
    @Autowired
    private DrugSimilarityRepository drugSimilarityRepository;

    @Override
    public List<Drug> getSimilarDrugs(Long drugId, Double minScore) {
        return drugRepository.findSimilarDrugs(drugId, minScore != null ? minScore : 0.7);
    }

    @Override
    public DrugSimilarity addSimilarity(Long drug1Id, Long drug2Id, Double score) throws BadRequestException {
        if (drug1Id.equals(drug2Id)) {
            throw new BadRequestException("Cannot add similarity between the same drug");
        }
        Drug drug1 = drugRepository.findById(drug1Id).orElse(null);
        Drug drug2 = drugRepository.findById(drug2Id).orElse(null);
        if (drug1 == null || drug2 == null){
            throw new BadRequestException("drug is null");
        }
        Optional<DrugSimilarity> existing = drugSimilarityRepository.findByDrugPair(drug1Id, drug2Id);
        if (existing.isPresent()) {
            throw new BadRequestException("Similarity relation already exists");
        }
        DrugSimilarity similarity = new DrugSimilarity();
        similarity.setDrug1(drug1);
        similarity.setDrug2(drug2);
        similarity.setSimilarity(score);

        return drugSimilarityRepository.save(similarity);
    }

    @Override
    public void deleteDrugSimilarity(Long drug1Id, Long drug2Id) throws BadRequestException {
        if (drug1Id.equals(drug2Id)) {
            throw new BadRequestException("DrugId Cannot be same");
        }
        Drug drug1 = drugRepository.findById(drug1Id).orElse(null);
        Drug drug2 = drugRepository.findById(drug2Id).orElse(null);
        if (drug1 == null || drug2 == null){
            throw new BadRequestException("drug is null");
        }
        Optional<DrugSimilarity> existing = drugSimilarityRepository.findByDrugPair(drug1Id, drug2Id);
        if (existing.isPresent()) {
            drugSimilarityRepository.deleteByDrugPair(drug1Id, drug2Id);
        }else {
            throw new BadRequestException("Relation not exists");
        }
    }
}
